// internal/dao/model/mysql/customer_one_touch_video_task_model.go
package mysql

import (
	"context"
	"errors"
	"go-api/internal/dao/model"
	"go-api/internal/dao/schema"
	"go-api/internal/svc"
	"gorm.io/gorm"
	"time"
)

const batchUpdateSize = 500

// CustomerOneTouchVideoTaskModel 定义一键成片任务模型
type CustomerOneTouchVideoTaskModel struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	db     *gorm.DB
}

// NewCustomerOneTouchVideoTaskModel 创建一键成片任务模型实例
func NewCustomerOneTouchVideoTaskModel(ctx context.Context, svcCtx *svc.ServiceContext) *CustomerOneTouchVideoTaskModel {
	return &CustomerOneTouchVideoTaskModel{
		ctx: ctx,
		db:  svcCtx.DbSelect.GetDb(ctx, model.DB),
	}
}

// FindTasksByStatus 根据状态查找任务
func (model *CustomerOneTouchVideoTaskModel) FindTasksByStatus(status int8) ([]*schema.CustomerOneTouchVideoTask, error) {
	var tasks []*schema.CustomerOneTouchVideoTask
	err := model.db.Where("status = ?", status).Find(&tasks).Error
	return tasks, err
}

// UpdateTaskStatus 更新任务状态
func (model *CustomerOneTouchVideoTaskModel) UpdateTaskStatus(id uint64, status int8) error {
	return model.db.Model(&schema.CustomerOneTouchVideoTask{}).Where("id = ?", id).Update("status", status).Error
}

// FindOne 根据 ID 查找单个任务
func (model *CustomerOneTouchVideoTaskModel) FindOne(id int64) (schema.CustomerOneTouchVideoTask, error) {
	var res schema.CustomerOneTouchVideoTask
	err := model.db.Model(&schema.CustomerOneTouchVideoTask{}).Where("id = ?", id).First(&res).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return res, nil
		}
		return res, err
	}
	return res, nil
}

// InsertSchema 插入新的任务
func (model *CustomerOneTouchVideoTaskModel) InsertSchema(data *schema.CustomerOneTouchVideoTask) error {
	data.CreatedAt = time.Now()
	return model.db.Create(data).Error
}

// UpdateByMap 根据 ID 和数据映射更新任务
func (model *CustomerOneTouchVideoTaskModel) UpdateByMap(id int64, data map[string]interface{}) error {
	return model.db.Model(&schema.CustomerOneTouchVideoTask{}).Where("id = ?", id).Updates(data).Error
}

// BatchUpdateStatus 批量更新任务状态
func (model *CustomerOneTouchVideoTaskModel) BatchUpdateStatus(ids []int64, status int8) error {
	return model.db.Model(&schema.CustomerOneTouchVideoTask{}).
		Where("id IN (?)", ids).
		Update("status", status).
		Error
}

// IterateTasksByStatus 使用 GORM 的游标查询避免内存溢出
func (model *CustomerOneTouchVideoTaskModel) IterateTasksByStatus(status int8, batchSize int, callback func([]*schema.CustomerOneTouchVideoTask)) {
	var lastID int64 = 0
	for {
		var tasks []*schema.CustomerOneTouchVideoTask
		model.db.Where("status = ? AND id > ?", status, lastID).
			Order("id ASC").
			Limit(batchSize).
			Find(&tasks)

		if len(tasks) == 0 {
			break
		}

		callback(tasks)
		lastID = tasks[len(tasks)-1].ID
	}
}
